# encoding=utf-8

from jinja2 import Environment, BaseLoader
import pymysql
import datetime
import os
import re


def to_camelcase(text):
    arr = filter(None, text.lower().split('_'))
    res = ''
    j = 0
    for i in arr:
        if j == 0:
            res = i
        else:
            res = res + i[0].upper() + i[1:]
        j += 1
    return res

def doCursor(database,sql):
    db = pymysql.connect(host='47.109.192.172',
                         port=3306,
                         user='root',
                         password='Lccloud@123',
                         database=database,
                         charset='utf8',
                         cursorclass=pymysql.cursors.DictCursor)
    try:
        cursor = db.cursor()
        sql = sql
        cursor.execute(sql)
        return cursor.fetchall()
    except Exception:
        print("sql 错误")

def readTableField(tableName):
    return doCursor("langchat",f"SHOW FULL COLUMNS FROM {tableName}")

def readTableInfo(tableName):
    return doCursor("information_schema",f"SELECT * FROM information_schema.TABLES WHERE TABLE_NAME = '{tableName}' and table_schema = 'langchat'")

def readAllTable():
    return doCursor("information_schema","SELECT * FROM information_schema.TABLES WHERE  table_schema = 'langchat'")


def Initial_Letter_Lower_Or_Upper(my_str, is_upper=False):
    if is_upper is False:
        return my_str[:1].lower() + my_str[1:]
    elif is_upper is True:
        return my_str[:1].upper() + my_str[1:]


def changeFiledType(datas):
    for data in datas:
        type = data["Type"]
        if "int" in type:
            data["Type"] = "Integer"
        if "bigint" in type:
            data["Type"] = "Long"
        if "varchar" in type:
            data["Type"] = "String"
        if "char" in type:
            data["Type"] = "String"
        if "blob" in type:
            data["Type"] = "byte[]"
        if "text" in type:
            data["Type"] = "String"
        if "integer" in type:
            data["Type"] = "Integer"
        if "tinyint" in type:
            data["Type"] = "Integer"
        if "smallint" in type:
            data["Type"] = "Integer"
        if "mediumint" in type:
            data["Type"] = "Integer"
        if "bit" in type:
            data["Type"] = "Boolean"
        if "json" in type:
            data["Type"] = "String"
        if "float" in type:
            data["Type"] = "Folat"
        if "double" in type:
            data["Type"] = "Double"
        if "decimal" in type:
            data["Type"] = "BigDecimal"
        if "boolean" in type:
            data["Type"] = "Boolean"
        if "date" in type:
            data["Type"] = "String"
        if "time" in type:
            data["Type"] = "LocalDateTime"
        if "datetime" in type:
            data["Type"] = "LocalDateTime"
        data["FieldLower"] = data["Field"]
        data["Field"] = to_camelcase(data["Field"])
        data["FieldUper"] = data["Field"][:1].upper() + data["Field"][1:]

    return datas


def create(jinja2Name, path, fileName, result, configuration):
    if not os.path.isdir(path):
        os.makedirs(path)
    with open(jinja2Name, mode="r", encoding="utf-8") as r:
        template_str = r.read()
        tpl = Environment(loader=BaseLoader).from_string(template_str)
        translateStr = tpl.render(datas=result, configuration=configuration)
        with open(path + fileName, mode="w", encoding="utf-8") as w:
            w.write(translateStr)


if __name__ == "__main__":
    tableCreateTime = "2022-11-09"
    tableDb = readAllTable()
    tables = []
    for table in tableDb:
        createTime = table["CREATE_TIME"].strftime("%Y-%m-%d")
        #if createTime == tableCreateTime:
        if 'rag_session' in table["TABLE_NAME"]:
            tables.append(table["TABLE_NAME"])
    projectName = "studyllm"
    packageName = "studyllm"
    module = "rag"
    workSpacePath = "C:\\Users\\wk\\IdeaProjects\\"  # "D:\\workspace\\java\\pyTest\\" #"C:\\Users\\Administrator\\IdeaProjects\\kw-framework\\"
    basicPath = f"{workSpacePath}{projectName}\\src\\main"
    path = basicPath + f"\\java\\com\\example\\{packageName}\\"
    mapperPath = f"{basicPath}\\resources\\mapper\\{module}\\"
    for table in tables:
        tableName = table.capitalize().title().replace("_","")
        logInfo = readTableInfo(table)
        configuration = {
            "basePackage": f"com.example.{packageName}",
            "javaName": tableName,
            "tableName": table,
            "module": module,
            "lowerTableName": Initial_Letter_Lower_Or_Upper(tableName),
            "date": datetime.datetime.now(),
            "tableCommont": logInfo[0]['TABLE_COMMENT']
        }
        result = readTableField(tableName=table)
        result = changeFiledType(result)
        translateStr = ""
        create("entity.jinja2", f"{path}entity\\{module}", f"\\{tableName}.java", result, configuration)
        create("mapper.jinja2", f"{path}mapper\\{module}", f"\\{tableName}Mapper.java", result, configuration)
        create("controller.jinja2", f"{path}controller\\{module}", f"\\{tableName}Controller.java", result , configuration)
        create("serviceImpl.jinja2", f"{path}service\\{module}", f"\\{tableName}Service.java", result , configuration)
        create("mapperXml.jinja2", mapperPath, f"\\{tableName}Mapper.xml", result, configuration)
